<template>
    <div class="study-screen" :style="{ backgroundImage: `url(${bgUrl})` }">
        <div class="blur-overlay"></div>
        <header class="topbar">
            <div class="top-left">
                <button class="icon-btn back-btn" aria-label="back" @click="backToHome">
                    <svg viewBox="0 0 24 24" width="24" height="24"><path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                </button>
                <div class="progress">{{ totalWords > 0 ? currentIndex + 1 : 0 }}/{{ totalWords }}</div>
            </div>
            <div class="actions">
                <button class="icon-btn" aria-label="star" @click="noop">★</button>
            </div>
        </header>

        <main class="panel">
            <div class="word-section">
                <h1 class="word">{{ currentWordData.word || '加载中...' }}</h1>
                <div class="word-info">
                    <button class="chip" @click="playAudio" :disabled="!currentWordData.audioUrl">
                        英 🔊
                    </button>
                    <span class="phonetic">{{ currentWordData.phonetic || '' }}</span>
                </div>

                <!-- 调试信息（开发时可见） -->
                <div v-if="isLoading" class="loading-indicator">加载中...</div>
                <div v-if="!isLoading && wordList.length === 0" class="empty-state">
                    暂无复习单词
                </div>

                <!-- 空白占位符 -->
                <div class="content-placeholder" v-show="!isAnswered">
                        <div class="blank long"></div>
                        <div class="blank short"></div>
                    </div>

                    <!-- 显示答案区域 -->
                <div class="word-detail-section" v-show="isAnswered">
                    <!-- 解析并显示单词的所有词性和意思 -->
                    <div class="word-meanings-list">
                        <div 
                            v-for="(meaningItem, index) in parsedMeanings" 
                            :key="index"
                            class="meaning-item"
                        >
                            <span class="part-of-speech">{{ meaningItem.partOfSpeech }}</span>
                            <span class="meaning-text">{{ meaningItem.meaning }}</span>
                        </div>
                    </div>
                    
                    <!-- 衍生词（如果有） -->
                    <div class="derivative-words" v-if="currentWordData.derivatives && currentWordData.derivatives.length > 0">
                        <div class="derivative-title">衍生词</div>
                        <div class="derivative-list">
                            <span 
                                v-for="(derivative, index) in currentWordData.derivatives" 
                                :key="index"
                                class="derivative-item"
                            >
                                {{ derivative }}
                            </span>
                        </div>
                    </div>
                    
                    <!-- 例句 -->
                    <div class="example-box" v-if="currentWordData.exampleSentenceEn || currentWordData.exampleSentenceCn">
                        <div class="example-en" v-if="currentWordData.exampleSentenceEn">{{ currentWordData.exampleSentenceEn }}</div>
                        <div class="example-cn" v-if="currentWordData.exampleSentenceCn">{{ currentWordData.exampleSentenceCn }}</div>
                            <div class="example-icon">💬</div>
                    </div>
                </div>
            </div>

            <div class="tips" v-if="!isAnswered">瞬间想起词义，选「认识」<br/>思考后想起词义，选「模糊」</div>

            <div class="choices">
                <template v-if="!isAnswered">
                    <button class="btn know" @click="handleAnswer('know')">认识</button>
                    <button class="btn blur" @click="handleAnswer('blur')">模糊</button>
                    <button class="btn forget" @click="handleAnswer('forget')">忘记了</button>
                </template>
                <template v-else>
                    <button class="btn next" @click="handleNext">下一词</button>
                </template>
            </div>
        </main>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { bgUrl } from '@/config/background.js'
import { fetchReviewWords, updateReviewRecord, saveStudySession } from '@/utils/api.js'

const router = useRouter()

// 数据状态
const wordList = ref([])
const currentIndex = ref(0)
const currentWordData = ref({})
const isAnswered = ref(false)
const isLoading = ref(false)

// 音频对象
let audio = null
let studyStartTime = null // 学习开始时间

// 计算属性
const totalWords = computed(() => wordList.value.length)

// 解析单词的所有词性和意思（处理多个词性的情况）
const parsedMeanings = computed(() => {
    if (!currentWordData.value.correctMeaning) return []
    
    const correctMeaning = currentWordData.value.correctMeaning.trim()
    const meanings = []
    
    // 匹配多个词性，例如："n.充裕,丰富" 或 "vt.标记;标签 vi.标记" 或 "n.狂喜;入迷Ecstasy.n.摇头丸"
    const partOfSpeechPattern = /([a-z]+\.|phr\.|phrv\.|usage\.|idm\.|vt\.|vi\.)/gi
    const matches = [...correctMeaning.matchAll(partOfSpeechPattern)]
    
    if (matches.length === 0) {
        // 如果没有词性标记，直接显示整个意思
        meanings.push({
            partOfSpeech: currentWordData.value.partOfSpeech || '',
            meaning: correctMeaning
        })
    } else {
        // 有多个词性，分别解析（详情页保留所有信息，包括衍生词）
        for (let i = 0; i < matches.length; i++) {
            const match = matches[i]
            const partOfSpeech = match[1]
            const startIndex = match.index + match[0].length
            const endIndex = i < matches.length - 1 ? matches[i + 1].index : correctMeaning.length
            let meaning = correctMeaning.substring(startIndex, endIndex).trim()
            
            // 清理多余的空格，但保留所有内容（包括衍生词）
            meaning = meaning.replace(/\s+/g, ' ').trim()
            
            if (meaning) {
                meanings.push({
                    partOfSpeech: partOfSpeech,
                    meaning: meaning
                })
            }
        }
    }
    
    return meanings.length > 0 ? meanings : [{
        partOfSpeech: currentWordData.value.partOfSpeech || '',
        meaning: correctMeaning
    }]
})

// 获取复习单词列表
async function loadWords() {
    try {
        isLoading.value = true
        console.log('开始获取复习单词...')
        const words = await fetchReviewWords(10)
        console.log('获取到的复习单词数据:', words)
        wordList.value = Array.isArray(words) ? words : []
        console.log('处理后的单词列表:', wordList.value)
        console.log('单词列表长度:', wordList.value.length)
        
        if (wordList.value.length > 0) {
            loadCurrentWord()
        } else {
            console.warn('没有复习单词数据')
            // 可以显示提示信息
        }
    } catch (error) {
        console.error('获取复习单词失败:', error)
        console.error('错误详情:', error.message)
        // 可以显示错误提示
    } finally {
        isLoading.value = false
    }
}

// 加载当前单词
function loadCurrentWord() {
    if (currentIndex.value >= wordList.value.length) {
        console.log('没有更多单词了')
        return
    }
    
    const wordData = wordList.value[currentIndex.value]
    console.log('加载当前单词，索引:', currentIndex.value, '数据:', wordData)
    
    if (!wordData) {
        console.warn('当前索引的单词数据为空')
        return
    }
    
    currentWordData.value = wordData
    isAnswered.value = false
    
    console.log('当前单词数据:', currentWordData.value)
    console.log('单词:', currentWordData.value.word)
    console.log('发音:', currentWordData.value.phonetic)
    console.log('意思:', currentWordData.value.correctMeaning)
    
    // 停止当前音频
    if (audio) {
        audio.pause()
        audio = null
    }
}

// 播放音频
function playAudio() {
    if (!currentWordData.value.audioUrl) return
    
    try {
        // 停止之前的音频
        if (audio) {
            audio.pause()
        }
        
        // 创建新的音频对象
        // 音频URL可能需要拼接基础路径
        const audioUrl = currentWordData.value.audioUrl.startsWith('http') 
            ? currentWordData.value.audioUrl 
            : `http://localhost:8080/${currentWordData.value.audioUrl}`
        
        audio = new Audio(audioUrl)
        audio.play().catch(error => {
            console.error('播放音频失败:', error)
        })
    } catch (error) {
        console.error('播放音频失败:', error)
}
}

// 处理用户选择
async function handleAnswer(type) {
    if (isAnswered.value) return
    
    // 立即更新状态，显示答案
        isAnswered.value = true
    
    // 调用后端API更新数据库记录（异步，不影响UI）
    updateReviewRecord(currentWordData.value.wordId, type).then((response) => {
        console.log('更新复习记录成功:', type)
        // 如果API返回了nextReviewAt，更新当前单词数据
        if (response && response.nextReviewAt) {
            const currentWord = wordList.value[currentIndex.value]
            if (currentWord) {
                currentWord.nextReviewAt = response.nextReviewAt
                // 同时更新currentWordData
                currentWordData.value.nextReviewAt = response.nextReviewAt
    }
}
    }).catch((error) => {
        console.error('更新复习记录失败:', error)
        // 可以显示错误提示，但不影响界面显示
    })
}

// 下一词
function handleNext() {
    if (currentIndex.value < wordList.value.length - 1) {
        currentIndex.value++
        loadCurrentWord()
    } else {
        // 所有单词复习完成，保存单词数据到sessionStorage
        const sessionId = Date.now().toString()
        const sessionData = {
            mode: 'review',
            wordList: wordList.value,
            wordIds: wordList.value.map(word => word.wordId),
            timestamp: Date.now()
        }
        sessionStorage.setItem(`study_session_${sessionId}`, JSON.stringify(sessionData))
        
        // 跳转到完成页面
        const wordIds = wordList.value.map(word => word.wordId).join(',')
        router.push({
            path: '/completion',
            query: {
                mode: 'review',
                wordIds: wordIds,
                isFirstGroup: 'false',
                sessionId: sessionId
            }
        })
    }
}

function backToHome() {
    router.push('/')
}

function noop() {}

onMounted(() => {
    // 记录学习开始时间
    studyStartTime = Date.now()
    console.log('复习开始，开始时间:', new Date(studyStartTime).toLocaleString())
    
    loadWords()
})

onBeforeUnmount(async () => {
    if (audio) {
        audio.pause()
        audio = null
    }
    
    // 计算学习时长并保存
    if (studyStartTime) {
        const endTime = Date.now()
        const duration = Math.floor((endTime - studyStartTime) / 1000 / 60) // 转换为分钟
        console.log('复习结束，时长:', duration, '分钟')
        
        if (duration > 0) {
            try {
                await saveStudySession(duration)
                console.log('学习时长保存成功')
            } catch (error) {
                console.error('保存学习时长失败:', error)
                // 保存失败不影响页面退出，静默处理
            }
        }
        studyStartTime = null
    }
})
</script>

<style scoped>
.study-screen {
    position: fixed;
    inset: 0;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    color: #0f172a;
    display: flex;
    flex-direction: column;
}

.blur-overlay {
    position: absolute;
    inset: 0;
    backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    -webkit-backdrop-filter: blur(35px) brightness(0.95) saturate(1.05);
    background: rgba(25, 35, 40, 0.25);
    z-index: 0;
}

.topbar {
    position: relative;
    z-index: 1;
    height: 56px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}
.top-left { display: flex; align-items: center; gap: 12px; }
.back-btn { display: flex; align-items: center; justify-content: center; }
.progress { color: #cbd5e1; font-weight: 600; font-size: 15px; line-height: 1; display: flex; align-items: center; }
.actions { display: flex; align-items: center; }
.icon-btn { border: none; background: transparent; cursor: pointer; color: #e2e8f0; padding: 0; display: inline-flex; align-items: center; justify-content: center; }

.panel { 
    position: relative; 
    z-index: 1; 
    flex: 1; 
    display: flex; 
    flex-direction: column; 
    align-items: flex-start; 
    padding: 40px 0 160px; 
    padding-left: calc(33.333% - 100px);
    width: 100%;
}
.word { margin: 0; font-size: 42px; font-weight: 700; letter-spacing: .5px; color: #ffffff; text-align: left; }
.word-info { margin-top: 6px; display: flex; align-items: center; gap: 10px; justify-content: flex-start; }
.chip { display: inline-block; background: rgba(255, 255, 255, 0.15); color: #e2e8f0; border-radius: 999px; padding: 3px 8px; font-size: 12px; border: none; cursor: pointer; transition: all 0.2s; }
.chip:hover { background: rgba(255, 255, 255, 0.25); }
.chip:disabled { opacity: 0.5; cursor: not-allowed; }
.phonetic { color: #cbd5e1; font-size: 13px; font-weight: 400; }


/* 空白占位符 */
.content-placeholder {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;
    max-width: 800px;
    margin-top: 12px;
}

.blank { 
    height: 24px; 
    border-radius: 10px; 
    background: rgba(255, 255, 255, 0.2); 
    backdrop-filter: blur(8px); 
}

.blank.long { width: 180px; }
.blank.short { width: 140px; }

/* 单词详情区域（参考学习页面） */
.word-detail-section {
    width: 100%;
    max-width: 800px;
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
}
}

.word-meanings-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 100%;
}

.meaning-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    color: #ffffff;
    line-height: 1.6;
}

.part-of-speech {
    font-size: 14px;
    color: #cbd5e1;
    font-weight: 500;
    flex-shrink: 0;
    min-width: 36px;
}

.meaning-text {
    font-size: 16px;
    color: #ffffff;
    flex: 1;
    border-bottom: 1px dotted rgba(255, 255, 255, 0.3);
    padding-bottom: 2px;
}

/* 衍生词 */
.derivative-words {
    padding: 16px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 12px;
    backdrop-filter: blur(8px);
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.derivative-title {
    font-size: 14px;
    color: #cbd5e1;
    font-weight: 600;
    margin-bottom: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.derivative-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.derivative-item {
    display: inline-block;
    padding: 6px 12px;
    background: rgba(255, 255, 255, 0.12);
    border-radius: 6px;
    font-size: 14px;
    color: #ffffff;
    font-weight: 500;
    border: 1px solid rgba(255, 255, 255, 0.15);
    transition: all 0.2s;
}

.derivative-item:hover {
    background: rgba(255, 255, 255, 0.18);
    border-color: rgba(255, 255, 255, 0.25);
}

.example-box {
    position: relative;
    background: rgba(15, 23, 42, 0.45);
    border-radius: 20px;
    padding: 18px 20px;
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    box-shadow: 0 32px 65px rgba(15, 23, 42, 0.45);
    width: 100%;
    max-width: 800px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
}

.example-en {
    font-size: 15px;
    color: rgba(226, 232, 240, 0.95);
    line-height: 1.6;
    margin-bottom: 8px;
    font-weight: 500;
    word-spacing: 0.2em;
    letter-spacing: 0.02em;
    text-align: left;
    width: 100%;
}

.example-cn {
    font-size: 14px;
    color: rgba(226, 232, 240, 0.75);
    line-height: 1.6;
    text-align: left;
    width: 100%;
}

.example-icon {
    position: absolute;
    bottom: 12px;
    right: 12px;
    font-size: 18px;
    opacity: 0.6;
}

.word-section {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 12px;
    width: 100%;
    max-width: 400px;
}

.content-placeholder {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;
    margin-top: 12px;
}

.tips { 
    position: fixed;
    bottom: 120px;
    left: 0;
    right: 0;
    text-align: center; 
    color: #9ca3af; 
    font-size: 14px; 
    line-height: 1.7; 
    z-index: 2;
    pointer-events: none;
    transition: opacity 0.3s ease-in-out;
}

.loading-indicator {
    color: #cbd5e1;
    font-size: 14px;
    margin-top: 12px;
}

.empty-state {
    color: #9ca3af;
    font-size: 14px;
    margin-top: 12px;
    padding: 12px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
}

.choices { 
    position: fixed;
    bottom: 38px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    z-index: 2;
}
.btn { appearance: none; border: none; background: transparent; font-size: 18px; font-weight: 500; color: #ffffff; position: relative; cursor: pointer; }
.btn::after { content: ""; position: absolute; left: 50%; transform: translateX(-50%); bottom: -8px; width: 18px; height: 3px; border-radius: 2px; opacity: .85; }
.know::after { background: #14b8a6; }
.blur::after { background: #f59e0b; }
.forget::after { background: #ef4444; }
.next::after { background: #14b8a6; }
.wrong::after { background: #ef4444; }
</style>

